package com.ncmmall.mall.controller.business.supplier;

import com.ncmmall.application.business.supplier.SupplierApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.excel.ExcelExports;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.lang.Dates;
import com.feijin.commons.securitys.MD5HashUtils;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.QMerchantGoodsChannel;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * @Description: 供应商管理
 * @Date: 2019-06-26 20:24
 */
@Controller
@RequestMapping(value = "/mall/supplier")
public class SupplierController {

    private final static Logger logger = LoggerFactory.getLogger(SupplierController.class);

    @Value("${web.domain}")
    private String webDomain;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private SupplierApplication supplierApplication;

    @Autowired
    private OperationLogApplication logApplication;


    /**
     * 分页条件筛选
     *
     * @param model
     * @param pageParams
     * @param supplier
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, WebUser supplier) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select u from WebUser u where u.role.name = 'SUPPLIER' ", params, supplier);
        QueryPage<WebUser> page = queryChannelService.findPage(hql, pageRequest.setParams(params), WebUser.class);

        //        page.setResult(Lists.transform(page.getResult(), new Function<WebUser, WebUser>() {
        //            @Nullable
        //            @Override
        //            public WebUser apply(@Nullable WebUser input) {
        //
        //                input.setGoodsNumber(queryChannelService.selectCount("select count(1) from mall_goods where supplier_id = :id and status = 3 ", ImmutableMap.of("id", input.getId())));
        //
        //                return input;
        //
        //            }
        //
        //        }));

        model.addAttribute("page", page).addAttribute("params", supplier);

        return "mall/supplier/list";
    }

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @param supplier
     */
    @RequestMapping(value = "/exports", method = RequestMethod.GET)
    private void exports(HttpServletRequest request, HttpServletResponse response, WebUser supplier) {
        Map<String, Object> params = Maps.newHashMap();
        String sql = "select u from WebUser u where u.role.name = 'SUPPLIER' ";
        String hql = builderSQL(sql, params, supplier);

        List<WebUser> result = queryChannelService.findAll(hql, params, WebUser.class);

        result = Lists.transform(result, new Function<WebUser, WebUser>() {
            @Nullable
            @Override
            public WebUser apply(@Nullable WebUser input) {

                input.setGoodsNumber(queryChannelService.selectCount("select count(1) from mall_goods where supplier_id = :id and status = 3 ", ImmutableMap.of("id", input.getId())));

                return input;

            }

        });

        Map<String, Object> data = ImmutableMap.of("result", result);
        ExcelExports document = new ExcelExports.Templates().formTemplate("suppliers.ftl").bind(data).store("suppliers.xls").build();

        try {
            document.generate();
            Webs.download(request, response, document.getFile(), "供应商名单" + Dates.transDateToStr(new Date()) + ".xls");

        } catch (Exception e) {
            logger.error("[导出异常]", e);
        }
    }

    /**
     * 查看供应商详情
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(id), WebUser.class);
        model.addAttribute("supplier", supplier).addAttribute("channels", queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(id), MerchantGoodsChannel.class));

        return "mall/supplier/detail";
    }

    /**
     * 添加供应商
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {

        model.addAttribute("supplier", new WebUser()).addAttribute("channels", queryChannelService.findAll(QGoodsChannel.goodsChannel.status.eq(1).and(QGoodsChannel.goodsChannel.level.eq(1).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0))), GoodsChannel.class)).addAttribute("_method", "POST");

        return "mall/supplier/form";
    }

    /**
     * 添加供应商
     *
     * @param supplier
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @ModelAttribute WebUser supplier) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be ajax !");
            }

            int isexist = queryChannelService.selectCount("select count(0) from security_web_user where username = :username and role_id = 5 ", ImmutableMap.of("username", supplier.getUsername()));
            if (isexist > 0) {
                return ImmutableMap.of("status", false, "message", "该账号已存在");
            }

            supplierApplication.createSupplier(supplier);
            logApplication.eventOfSystem(Securitys.currentUser(), "添加供应商账号" + supplier.getUsername(), Securitys.getIp(request));

        } catch (Exception e) {
            logger.error("[添加供应商异常]", e);
            return ImmutableMap.of("status", false, "message", "添加供应商异常");
        }

        return ImmutableMap.of("status", true);
    }

    /**
     * 编辑供应商信息
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(Model model, @PathVariable("id") long id) {

        WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(id), WebUser.class);

        List<MerchantGoodsChannel> goodsChannels = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(id), MerchantGoodsChannel.class);
        List<String> channelNames = Lists.transform(goodsChannels, new Function<MerchantGoodsChannel, String>() {
            @Nullable
            @Override
            public String apply(@Nullable MerchantGoodsChannel input) {
                return input.getChannel().getName();
            }
        });

        model.addAttribute("supplier", supplier).addAttribute("channels", queryChannelService.findAll(QGoodsChannel.goodsChannel.status.eq(1).and(QGoodsChannel.goodsChannel.level.eq(1).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0))), GoodsChannel.class)).addAttribute("channelNames", channelNames).addAttribute("_method", "PUT");

        return "mall/supplier/form";
    }

    /**
     * 编辑供应商信息
     *
     * @param supplier
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @ModelAttribute WebUser supplier) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be ajax !");
            }

            supplierApplication.modifySupplier(supplier);
            logApplication.eventOfSystem(Securitys.currentUser(), "编辑供应商账号" + supplier.getUsername(), Securitys.getIp(request));

        } catch (Exception e) {
            logger.error("[编辑供应商异常]", e);
            return ImmutableMap.of("status", false, "message", "编辑供应商异常");
        }

        return ImmutableMap.of("status", true);
    }

    /**
     * 禁用
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> disable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(id), WebUser.class);

            supplierApplication.disable(supplier);
            logApplication.eventOfSystem(Securitys.currentUser(), "禁止供应商登录账号" + supplier.getUsername(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[锁定供应商异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 启用
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/enabled", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> enabled(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(id), WebUser.class);

            supplierApplication.enabled(supplier);
            logApplication.eventOfSystem(Securitys.currentUser(), "允许供应商登录账号" + supplier.getUsername(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[锁定供应商异常]", e);
            return ImmutableMap.of("status", false);
        }
    }


    /**
     * 批量禁用
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/disables", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> disables(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            supplierApplication.disables(Lists.transform(ids, new Function<String, WebUser>() {
                @Nullable
                @Override
                public WebUser apply(@Nullable String input) {
                    WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(Longs.tryParse(input)), WebUser.class);
                    return supplier;
                }
            }));

            logApplication.eventOfSystem(Securitys.currentUser(), "批量禁止供应商登录账号", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[禁用供应商异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 批量启用
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/enables", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> enables(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("ids") String data) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            List<String> ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

            supplierApplication.enables(Lists.transform(ids, new Function<String, WebUser>() {
                @Nullable
                @Override
                public WebUser apply(@Nullable String input) {
                    WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(Longs.tryParse(input)), WebUser.class);
                    return supplier;
                }
            }));

            logApplication.eventOfSystem(Securitys.currentUser(), "批量允许供应商登录账号", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[启用供应商异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 重置密码
     *
     * @param request
     * @param requestWith
     * @param params
     * @return
     */
    @RequestMapping(value = "/resetPassword", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> resetPassword(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, WebUser params) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(params.getId()), WebUser.class);

            supplierApplication.modifyPassword(supplier, MD5HashUtils.MD5("123456"));

            logApplication.eventOfSystem(Securitys.currentUser(), "重置供应商密码" + supplier.getUsername(), Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[重置会员密码异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 设为自营供应商
     *
     * @param request
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/selfSupport", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> selfSupport(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(id), WebUser.class);

            supplierApplication.selfSupport(supplier);
            logApplication.eventOfSystem(Securitys.currentUser(), "设置成为自营供应商" + supplier.getUsername(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[锁定供应商异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 取消自营
     *
     * @param request
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/cancelSelfSupport", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> cancelSelfSupport(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(id), WebUser.class);

            supplierApplication.cancelSelfSupport(supplier);
            logApplication.eventOfSystem(Securitys.currentUser(), "取消自营供应商" + supplier.getUsername(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[锁定供应商异常]", e);
            return ImmutableMap.of("status", false);
        }
    }


    /**
     * 条件查询
     *
     * @param sql
     * @param params
     * @param supplier
     * @return
     */
    private String builderSQL(String sql, Map<String, Object> params, WebUser supplier) {

        if (!Strings.isNullOrEmpty(supplier.getRealName())) {
            sql += " and u.realName like :realname ";
            params.put("realname", "%" + supplier.getRealName() + "%");
        }

        if (!Strings.isNullOrEmpty(supplier.getMobile())) {
            sql += " and u.mobile like :mobile ";
            params.put("mobile", "%" + supplier.getMobile() + "%");
        }

        if (!Strings.isNullOrEmpty(supplier.getUsername())) {
            sql += " and u.username like :username ";
            params.put("username", "%" + supplier.getUsername() + "%");
        }

        if (!Strings.isNullOrEmpty(supplier.getShopName())) {
            sql += " and u.shopName like :shopname ";
            params.put("shopname", "%" + supplier.getShopName() + "%");
        }

        if (supplier.getMainType() > 0) {
            sql += " and u.mainType = :maintype ";
            params.put("maintype", supplier.getMainType());
        }

        if (!Strings.isNullOrEmpty(supplier.getOrderByGoodsNumber())) {
            sql += " order by u.goodsNumber " + supplier.getOrderByGoodsNumber();
        }

        if (!Strings.isNullOrEmpty(supplier.getOrderByMerchantEnterTime())) {
            sql += " order by u.supplierEnterTime " + supplier.getOrderByMerchantEnterTime();
        }

        if (!Strings.isNullOrEmpty(supplier.getOrderByTotalOrderAmount())) {
            sql += " order by u.totalOrderAmount " + supplier.getOrderByTotalOrderAmount();
        }

        if (!Strings.isNullOrEmpty(supplier.getOrderByTotalOrderNumber())) {
            sql += " order by u.totalOrderNumber " + supplier.getOrderByTotalOrderNumber();
        }

        return sql;
    }


}
